package com.zbs.framework.dao.passport.wechat.service.impl;

import com.zbs.framework.common.utils.Constant;
import com.zbs.framework.common.utils.ErrorAssert;
import com.zbs.framework.dao.passport.base.repository.MNAccountRepository;
import com.zbs.framework.dao.passport.entity.AcctWechat;
import com.zbs.framework.dao.passport.entity.MNAccount;
import com.zbs.framework.dao.passport.wechat.WechatProperties;
import com.zbs.framework.dao.passport.wechat.repository.AcctWechatRepository;
import com.zbs.framework.dao.passport.wechat.service.WechatAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.user.User;

@Service
@Transactional
public class WechatAccountServiceImpl implements WechatAccountService {

    @Autowired
    private AcctWechatRepository acctWechatRepository;

    @Autowired
    private MNAccountRepository accountRepository;

    @Autowired
    private WechatProperties properties;

    @Override
    public MNAccount findAccount(String openId) {
        // 参数检查
        ErrorAssert.hasLength(openId, "OpenId can not be empty!");
        return acctWechatRepository.findAccount(openId);
    }

    @Override
    public AcctWechat create(String openId) {
        // 参数检查
        ErrorAssert.hasLength(openId, "OpenId can not be empty!");
        // 创建账号
        MNAccount account = new MNAccount(Constant.YES);
        accountRepository.save(account);
        // 创建微信账号
        AcctWechat aw = new AcctWechat(openId, account.getUuid());
        acctWechatRepository.save(aw);
        return aw;
    }

    @Override
    public SnsToken getSnsToken(String code) {
        // 参数检查
        ErrorAssert.notNull(code, "Code can not be empty!");
        SnsToken token = SnsAPI.oauth2AccessToken(properties.getAppId(), properties.getAppSecret(), code);
        ErrorAssert.notNull(token, "获取微信token失败");
        ErrorAssert.isTrue(!StringUtils.hasLength(token.getErrcode()),
                String.format("获取微信token失败 errCode: %s, errMsg: %s", token.getErrcode(), token.getErrmsg()));
        return token;
    }

    @Override
    public User getWechatUserInfo(SnsToken token) {
        // 参数检查
        ErrorAssert.notNull(token, "Token can not be null");
        User user = SnsAPI.userinfo(token.getAccess_token(), token.getOpenid(), "zh_CN");
        if (user == null || StringUtils.hasLength(user.getErrcode())) return null;
        return user;
    }
}
